using Microsoft.AspNetCore.Mvc;
using KnowledgeQA.Models.DTOs;
using KnowledgeQA.Services.Interfaces;

namespace KnowledgeQA.API.Controllers
{
    /// <summary>
    /// 问答控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class QAController : ControllerBase
    {
        private readonly IQAService _qaService;
        private readonly ILogger<QAController> _logger;

        public QAController(IQAService qaService, ILogger<QAController> logger)
        {
            _qaService = qaService;
            _logger = logger;
        }

        /// <summary>
        /// 单轮问答
        /// </summary>
        /// <param name="request">问答请求</param>
        /// <returns>问答响应</returns>
        [HttpPost("ask")]
        public async Task<ActionResult<AskQuestionResponse>> AskQuestion([FromBody] AskQuestionRequest request)
        {
            try
            {
                var response = await _qaService.AskQuestionAsync(request);
                return Ok(BaseResponse<AskQuestionResponse>.SuccessResult(response));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "问答失败");
                return StatusCode(500, BaseResponse<AskQuestionResponse>.ErrorResult("问答失败"));
            }
        }

        /// <summary>
        /// 创建聊天会话
        /// </summary>
        /// <param name="request">创建请求</param>
        /// <returns>会话信息</returns>
        [HttpPost("sessions")]
        public async Task<ActionResult<ChatSessionDTO>> CreateSession([FromBody] CreateSessionRequest request)
        {
            try
            {
                var session = await _qaService.CreateSessionAsync(request);
                return CreatedAtAction(nameof(GetSession), new { sessionId = session.Id }, 
                    BaseResponse<ChatSessionDTO>.SuccessResult(session));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建会话失败");
                return StatusCode(500, BaseResponse<ChatSessionDTO>.ErrorResult("创建会话失败"));
            }
        }

        /// <summary>
        /// 获取会话列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <returns>会话列表</returns>
        [HttpGet("sessions")]
        public async Task<ActionResult<PagedResponse<ChatSessionDTO>>> GetSessions(
            [FromQuery] string? userId = null,
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 20)
        {
            try
            {
                var sessions = await _qaService.GetSessionsAsync(userId, pageIndex, pageSize);
                return Ok(sessions);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取会话列表失败");
                return StatusCode(500, BaseResponse<List<ChatSessionDTO>>.ErrorResult("获取会话列表失败"));
            }
        }

        /// <summary>
        /// 根据ID获取会话
        /// </summary>
        /// <param name="sessionId">会话ID</param>
        /// <returns>会话信息</returns>
        [HttpGet("sessions/{sessionId}")]
        public async Task<ActionResult<ChatSessionDTO>> GetSession(int sessionId)
        {
            try
            {
                var session = await _qaService.GetSessionByIdAsync(sessionId);
                if (session == null)
                {
                    return NotFound(BaseResponse<ChatSessionDTO>.ErrorResult("会话不存在"));
                }
                return Ok(BaseResponse<ChatSessionDTO>.SuccessResult(session));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取会话失败，ID: {SessionId}", sessionId);
                return StatusCode(500, BaseResponse<ChatSessionDTO>.ErrorResult("获取会话失败"));
            }
        }

        /// <summary>
        /// 删除会话
        /// </summary>
        /// <param name="sessionId">会话ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("sessions/{sessionId}")]
        public async Task<ActionResult> DeleteSession(int sessionId)
        {
            try
            {
                var result = await _qaService.DeleteSessionAsync(sessionId);
                if (result)
                {
                    return Ok(BaseResponse<bool>.SuccessResult(true, "会话删除成功"));
                }
                return NotFound(BaseResponse<bool>.ErrorResult("会话不存在"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除会话失败，ID: {SessionId}", sessionId);
                return StatusCode(500, BaseResponse<bool>.ErrorResult("删除会话失败"));
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="request">发送请求</param>
        /// <returns>消息信息</returns>
        [HttpPost("chat")]
        public async Task<ActionResult<ChatMessageDTO>> SendMessage([FromBody] SendMessageRequest request)
        {
            try
            {
                var message = await _qaService.SendMessageAsync(request);
                return Ok(BaseResponse<ChatMessageDTO>.SuccessResult(message));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送消息失败");
                return StatusCode(500, BaseResponse<ChatMessageDTO>.ErrorResult("发送消息失败"));
            }
        }

        /// <summary>
        /// 获取会话消息列表
        /// </summary>
        /// <param name="sessionId">会话ID</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <returns>消息列表</returns>
        [HttpGet("sessions/{sessionId}/messages")]
        public async Task<ActionResult<PagedResponse<ChatMessageDTO>>> GetSessionMessages(
            int sessionId,
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 50)
        {
            try
            {
                var messages = await _qaService.GetSessionMessagesAsync(sessionId, pageIndex, pageSize);
                return Ok(messages);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取会话消息失败，会话ID: {SessionId}", sessionId);
                return StatusCode(500, BaseResponse<List<ChatMessageDTO>>.ErrorResult("获取会话消息失败"));
            }
        }

        /// <summary>
        /// 提交用户反馈
        /// </summary>
        /// <param name="request">反馈请求</param>
        /// <returns>提交结果</returns>
        [HttpPost("feedback")]
        public async Task<ActionResult> SubmitFeedback([FromBody] UserFeedbackRequest request)
        {
            try
            {
                var result = await _qaService.SubmitFeedbackAsync(request);
                if (result)
                {
                    return Ok(BaseResponse<bool>.SuccessResult(true, "反馈提交成功"));
                }
                return BadRequest(BaseResponse<bool>.ErrorResult("反馈提交失败"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "提交反馈失败");
                return StatusCode(500, BaseResponse<bool>.ErrorResult("提交反馈失败"));
            }
        }

        /// <summary>
        /// 导出会话记录
        /// </summary>
        /// <param name="sessionId">会话ID</param>
        /// <param name="format">导出格式</param>
        /// <returns>导出内容</returns>
        [HttpGet("sessions/{sessionId}/export")]
        public async Task<ActionResult> ExportSession(int sessionId, [FromQuery] string format = "json")
        {
            try
            {
                var content = await _qaService.ExportSessionAsync(sessionId, format);
                var fileName = $"session_{sessionId}_{DateTime.Now:yyyyMMddHHmmss}.{format}";
                
                return File(System.Text.Encoding.UTF8.GetBytes(content), "text/plain", fileName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出会话失败，会话ID: {SessionId}", sessionId);
                return StatusCode(500, BaseResponse<string>.ErrorResult("导出会话失败"));
            }
        }

        /// <summary>
        /// 获取问答统计信息
        /// </summary>
        /// <returns>统计信息</returns>
        [HttpGet("stats")]
        public async Task<ActionResult<QAStats>> GetQAStats()
        {
            try
            {
                var stats = await _qaService.GetQAStatsAsync();
                return Ok(BaseResponse<QAStats>.SuccessResult(stats));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取问答统计信息失败");
                return StatusCode(500, BaseResponse<QAStats>.ErrorResult("获取问答统计信息失败"));
            }
        }
    }
} 